/**
 * Copyright (c) 2017 ucsmy.com, All rights reserved.
 */
package itsm.isperp.module.controller.api.wechat.v2;

import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.knowledge.KngKnowledgeCategory;
import itsm.isperp.module.entity.knowledge.KngKnowledgeItem;
import itsm.isperp.module.service.knowledge.KngKnowledgeCategoryService;
import itsm.isperp.module.service.knowledge.KngKnowledgeCommentService;
import itsm.isperp.module.service.knowledge.KngKnowledgeItemService;
import itsm.isperp.workflow.service.BpmProcessRunService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: legen
 * @Created Date: 2017-10-09-0009.
 * @LastModifyDate: 2017-10-09-0009.
 * @LastModifyBy: legen
 * @Version:
 */
@Controller
@RequestMapping("api/wechat/v2/knowledge")
public class KnowledgeController extends BaseController {

    @Autowired
    protected KngKnowledgeCategoryService kngKnowledgeCategoryService;

    @Autowired
    protected KngKnowledgeItemService kngKnowledgeItemService;

    @Autowired
    protected KngKnowledgeCommentService kngKnowledgeCommentService;

    @Resource(name = "bpmProcessRunService")
    private BpmProcessRunService bpmProcessRunService;

    /**
     * 获取知识分类
     */
    @RequestMapping("category")
    @ResponseBody
    public List<KngKnowledgeCategory> department(String username) {
        List<KngKnowledgeCategory> tree = kngKnowledgeCategoryService.getTree(null, false, "id", "name", "parent_id", "treenode_path");
        return tree;
    }

    /**
     * 获取最新、热门知识
     */
    @RequestMapping("top")
    @ResponseBody
    public Map<String, Object> top(String username) {
        List<Map<String, Object>> warmTop = kngKnowledgeItemService.getTop10Item();
        warmTop = filterColumns(warmTop, "id", "title", "publish_date");

        List<KngKnowledgeItem> newKnowledget = kngKnowledgeItemService.getNewTop10Item(10, "");
        List<Map<String, Object>> newTop = new ArrayList<>();
        for (KngKnowledgeItem knowledget : newKnowledget) {
            Map<String, Object> newMap = new HashMap<>();
            newMap.put("id", knowledget.getId());
            newMap.put("title", knowledget.getTitle());
            newMap.put("publish_date", knowledget.getPublishDate());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("warn", warmTop);
        result.put("new", newTop);
        return result;
    }

    /**
     * 获取我发布的知识
     */
    @RequestMapping("myPublished")
    @ResponseBody
    public List<Map<String, Object>> myPublished(String username) {
        JqGridRequest request = new JqGridRequest();
        request.setPageable(false);
        request.setSelectColumns("id", "title", "publish_date", "create_date");
        request.setSort("create_date", Sort.Direction.DESC);
        request.addFilterRule("creator", JqGridFilterRuleOp.eq, username);

        return kngKnowledgeItemService.findAllDetailByRequest(request);
    }

    /**
     * 查询知识
     */
    @RequestMapping("query")
    @ResponseBody
    public List<Map<String, Object>> query(String username, String keyword) {
        JqGridRequest request = new JqGridRequest();
        request.setPageable(false);
        request.setSelectColumns("id", "title", "publish_date");
        request.setSort("publish_date", Sort.Direction.ASC);
        request.setSearchString("status = '发布' and (title like '%" + keyword + "%' or keyword like '%" + keyword + "%' or contents like '%" + keyword + "%')");

        return kngKnowledgeItemService.findAllDetailByRequest(request);
    }

    /**
     * 查询知识
     */
    @RequestMapping("list")
    @ResponseBody
    public List<Map<String, Object>> list(String username, String kngKnowledgeCategoryName) {
        JqGridRequest categoryRequest = new JqGridRequest();
        categoryRequest.setSelectColumns("id", "name");
        categoryRequest.addFilterRule("name", JqGridFilterRuleOp.eq, kngKnowledgeCategoryName);
        List<KngKnowledgeCategory> categorys = kngKnowledgeCategoryService.findAll(categoryRequest);
        String kngKnowledgeCategoryId = "";
        if (categorys.size() > 0) {
            kngKnowledgeCategoryId = categorys.get(0).getId();
        }

        JqGridRequest request = new JqGridRequest();
        request.setPageable(false);
        request.setSelectColumns("id", "title", "publish_date");
        request.setSort("publish_date", Sort.Direction.ASC);
        request.addFilterRule("status", JqGridFilterRuleOp.eq, "发布");
        request.addFilterRule("kng_knowledge_category_id", JqGridFilterRuleOp.eq, kngKnowledgeCategoryId);

        return kngKnowledgeItemService.findAllDetailByRequest(request);
    }

    /**
     * 知识明细
     */
    @RequestMapping(value = "detail")
    @ResponseBody
    public Map<String, Object> detail(String username, String id) {
        JqGridRequest request = new JqGridRequest();
        request.setPageable(false);
        request.setSelectColumns("id", "title", "contents", "publish_date", "read_times", "commentary_times", "treenode_name_path", "creator");
        request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
        Map<String, Object> data = kngKnowledgeItemService.findOneDetailByRequest(request);

        JqGridRequest commentRequest = new JqGridRequest();
        commentRequest.setSelectColumns("ifnull(sum(case comment_type WHEN 1 THEN 1 ELSE 0 END),0) AS good", "ifnull(sum(case comment_type WHEN 0 THEN 1 ELSE 0 END),0) AS bad");
        commentRequest.addFilterRule("kng_knowledge_itemid", JqGridFilterRuleOp.eq, id);
        Map<String, Object> commentMap = kngKnowledgeCommentService.findOneDetailByRequest(commentRequest);
        data.put("good", commentMap.get("good"));
        data.put("bad", commentMap.get("bad"));

        List<Map<String, Object>> comments = kngKnowledgeCommentService.findAllDetailByKnowledgeId(data.get("id").toString());
        comments = filterColumns(comments, "content", "commenter_name", "comment_time", "comment_type");

        Map<String, Object> map =new HashMap<>();
        map.put("data", data);
        map.put("comments", comments);
        
        //kngKnowledgeItemService.onclickPoint(username,id);

        return map;
    }

    /**
     * 添加知识
     */
    @RequestMapping(value = "new", method = RequestMethod.POST)
    @ResponseBody
    public String newKnowledge(String username, @RequestBody BpmData<KngKnowledgeItem> bpmData)
            throws Exception {

        login(username);

        KngKnowledgeItem model = bpmData.getData();
        model.setId(HibernateUUIDGenerator.generate());

        kngKnowledgeItemService.saveOrUpdate(model);
        bpmProcessRunService.startProcess(username, KNOWLEDGE_PROCESS, model.getId(), bpmData.getSuggestion());
        saveImages(model.getId(), bpmData.getImages());

        return model.getId();
    }

    @Autowired
    private WechatController wechatController;

    /**
     * 评论知识
     */
    @RequestMapping(value = "comment", method = RequestMethod.POST)
    @ResponseBody
    public void comment(String username, @RequestBody Map<String, Object> data, HttpServletRequest request)
            throws Exception {

        login(username);
        Integer commentType = (Integer) data.get("commentaryType");

        String id = (String) data.get("id");
        kngKnowledgeCommentService.addCommont(id, (String) data.get("comment"), commentType, username);

        Map<String, Object> detail = (Map<String, Object>) this.detail(username, id).get("data");

        if (commentType == 0) {
            this.wechatController.sendMessage(detail.get("title") + " 求助信息收到了回复", (String) detail.get("creator"), request);
        }
    }
}
